<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/" class="search-form">
  <van-search
    v-model="value"
    show-action
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @cancel="onCancel"
    background="#3296fa"
    @focus='isResultShow=false'
  />
</form>
<!-- 搜索结果 -->
<SearchResult
v-if="isResultShow"
:searchText="value"
></SearchResult>
<!-- 联想建议 -->
<SearchSuggestion
v-else-if="value"
:searchText="value"
@search="onSearch"
></SearchSuggestion>
<!-- 搜索记录 -->
<SearchHistory
v-else
:searchHistories="searchHistories"
@deleteSearchHistory='deleteSearchHistory'
@deleteAllSearchHistories='deleteAllSearchHistories'
@search='onSearch'
></SearchHistory>
  </div>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { setItem, getItem } from '@/utils/storage'
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import router from '@/router/index'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  setup () {
    const isResultShow = ref(false)// 搜索结果是否展示
    const value = ref('')// 输入框内容
    const searchHistories = reactive(getItem('TOUTIAO_SEARCH_HISTORIES') || [])// 搜索历史
    // 按下搜索/回车触发
    const onSearch = (val) => {
      value.value = val// 更新搜索框内容
      const index = searchHistories.indexOf(val)
      if (index !== -1) {
        searchHistories.splice(index, 1)// 有重复的话就删掉
      }
      searchHistories.unshift(val)// 储存搜索记录
      isResultShow.value = true
    }
    // 取消
    const onCancel = () => {
      router.go(-1)
    }
    // 删除单个历史记录
    function deleteSearchHistory (index) {
      searchHistories.splice(index, 1)
    }
    // 删除全部历史记录
    function deleteAllSearchHistories () {
      searchHistories.splice(0, searchHistories.length)// 清空数组的神来之笔
    }
    watch(
      () => searchHistories, (newValue) => {
        setItem('TOUTIAO_SEARCH_HISTORIES', newValue)
      }
    )
    return {
      value,
      onSearch,
      onCancel,
      isResultShow,
      searchHistories,
      deleteSearchHistory,
      deleteAllSearchHistories
    }
  }
}
</script>

<style lang='less' scoped>
.search-container{
  padding-top: 108px;
  /deep/.van-search__action{
    color: #fff;
  }
  .search-form{
    position: fixed;
    width: 100%;
    top: 0;
    z-index: 1;
  }
}
</style>
